package ru.ksu.ktk.diploma.sdi.schema.convertor.impl;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

import ru.ksu.ktk.diploma.sdi.schema.convertor.ConvertationException;
import ru.ksu.ktk.diploma.sdi.schema.convertor.OWLTransformerFactory;
import ru.ksu.ktk.diploma.sdi.schema.convertor.XML2OWLConvertor;

/**
 * @author: NZhiltsov
 * Date: 25.01.2009
 * Time: 21:33:30
 */
public class XML2OWLConvertorImpl implements XML2OWLConvertor {
    private OWLTransformerFactory transformerFactory;
    private static final String BASE_URI = "http://www.rbm.ru";

    public OntModel convert(InputStream xmlStream, String projectAlias) throws
            FileNotFoundException {
        OntModel resultModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);

        Source srcXML = getSource(xmlStream);

        ByteArrayOutputStream resXMLOutput = new ByteArrayOutputStream();
        Result resXML = new StreamResult(resXMLOutput);
        try {
            getTransformer().setParameter("prefixID", new Integer(2));
            getTransformer().setParameter("projectAlias", projectAlias);
            getTransformer().transform(srcXML, resXML);
        } catch (TransformerException e) {
            throw new ConvertationException(e);
        }

        InputStream resXMLInput = new ByteArrayInputStream(resXMLOutput.toByteArray());
        resultModel.read(resXMLInput, BASE_URI, "RDF/XML-ABBREV");
        return resultModel;
    }

    private Transformer getTransformer() throws TransformerConfigurationException {
        return transformerFactory.getTransformer();
    }

    private Source getSource(InputStream xmlStream) {
        Source srcXML = new StreamSource(xmlStream);
        return srcXML;
    }

    public OWLTransformerFactory getTransformerFactory() {
        return transformerFactory;
    }

    public void setTransformerFactory(OWLTransformerFactory transformerFactory) {
        this.transformerFactory = transformerFactory;
    }
}
